package com.wiz.weixin.controllor;

import java.io.IOException;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.wiz.weixin.TO.MemberPasswordTO;
import com.wiz.weixin.VO.AuthVO;
import com.wiz.weixin.common.GlobalConstant;
import com.wiz.weixin.common.TencentConstant;
import com.wiz.weixin.manager.TencentManager;
import com.wiz.weixin.service.ScanRefuelingService;
import com.wiz.weixin.util.PastUtil;

/**
 * 扫一扫加油
 * @author xxy
 *
 */
@Controller
@RequestMapping("/scanRefueling")
public class ScanRefuelingControllor {
	
	@Resource
	private TencentManager tencentManager;
	@Resource
	private ScanRefuelingService scanRefuelingService;
	/**扫一扫测试*/
	@RequestMapping(value="/toEditRichScan")
	public String toEditRichScan(HttpServletRequest request,HttpServletResponse response,
			HttpSession session, Model model)throws ServletException, IOException {
		 // 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8"); 
        String code=request.getParameter("code");//签名串
        
        String appid =  TencentConstant.WX_APP_ID; //随机字符串
        String ticket = GlobalConstant.tencent_wx_ticket;
        try {
			String openid = tencentManager.getOpenId(code);
			Map<String, String>map = PastUtil.getParam(appid, ticket);
			map.put("code", code);
			System.out.println("code=============>"+code);
			map.put("openid", openid);
			model.addAttribute("map", map);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
		return "/richScan/scan";
	}
	/**扫一扫*/
	@RequestMapping(value="/toAuthorization")
	public String toAuthorization(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "fpId", required=true) String fpId,
			HttpSession session, Model model)throws ServletException, IOException {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
		request.setCharacterEncoding("UTF-8");  
		response.setCharacterEncoding("UTF-8"); 
		
		String code = request.getParameter("code");
		try {
			String agent=request.getHeader("User-Agent").toLowerCase();
            if(!agent.contains("micromessenger")){
            	throw new Exception("请使用微信自带的浏览注册！");
            }
			String openid = tencentManager.getOpenId(code);
			session.setAttribute("openid", openid);
			Map<String,Object>map = scanRefuelingService.hqbyFpId(fpId, openid);
			
			model.addAttribute("map", map);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", e.getMessage());
			return "/scanRefueling/checkin_fail";
		}
		
		
		
		return "/scanRefueling/refuel";
	}
	/**授权*/
	@RequestMapping(value="/authorization", method=RequestMethod.POST)
	public String authorization(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "fpId", required=true) String fpId,
			@RequestParam(value = "stationId", required=true) String stationId,
			@RequestParam(value = "memberId", required=true) String memberId,
			@RequestParam(value = "memberFrozenAmount", required=true) Double memberFrozenAmount,
			@RequestParam(value = "isCheckFuellingPw", required=true) Long isCheckFuellingPw,
			HttpSession session, Model model)throws ServletException, IOException {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
		request.setCharacterEncoding("UTF-8");  
		response.setCharacterEncoding("UTF-8"); 
		
		AuthVO authVO = new AuthVO(fpId, stationId, memberId, memberFrozenAmount, 1);
		try {
			String agent=request.getHeader("User-Agent").toLowerCase();
            if(!agent.contains("micromessenger")){
            	throw new Exception("请使用微信自带的浏览注册！");
            }
			
			//判断是否需要验证加油密码
			if(isCheckFuellingPw != null && isCheckFuellingPw == 1){
				model.addAttribute("authVO", authVO);
				return "/scanRefueling/toPassword";
			}
			scanRefuelingService.authorization(authVO);
			return "/scanRefueling/authorization";
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", e.getMessage());
			return "/scanRefueling/checkin_fail";
		}
		
		
	}
	/**验证密码、授权*/
	@RequestMapping(value="/verifyAuth",method=RequestMethod.POST)
	public String verifyAuth(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "fpId", required=true) String fpId,
			@RequestParam(value = "stationId", required=true) String stationId,
			@RequestParam(value = "memberId", required=true) String memberId,
			@RequestParam(value = "memberFrozenAmount", required=true) Double memberFrozenAmount,
			@RequestParam(value = "password", required=true) String password,
			HttpSession session, Model model)throws ServletException, IOException {
		 // 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8"); 
        
        AuthVO authVO = new AuthVO(fpId, stationId, memberId, memberFrozenAmount, 1);
        try {
        	
        	List<MemberPasswordTO>list = scanRefuelingService.passwordByMemberId(memberId, password);
        	if(list == null || list.size()<=0){
        		throw new Exception("密码错误");
        	}
        	scanRefuelingService.authorization(authVO);
        	return "/scanRefueling/authorization";
        	
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", e.getMessage());
			return "/scanRefueling/checkin_fail";
		}

        
	}
	/**积分授权*/
	@RequestMapping(value="/pointAuth")
	public String pointAuth(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "fpId", required=true) String fpId,
			@RequestParam(value = "stationId", required=true) String stationId,
			@RequestParam(value = "memberId", required=true) String memberId,
			HttpSession session, Model model)throws ServletException, IOException {
		
		
		 AuthVO authVO = new AuthVO(fpId, stationId, memberId, 0.0, 2);
        try {
			scanRefuelingService.authorization(authVO);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", e.getMessage());
			return "/scanRefueling/checkin_fail";
		}
		
		return "/scanRefueling/point_success";
		
	}

}
